﻿using B.S.DataBase.MyProject.Domain.SalesReports;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using MediatR;
using T.E.ERP.Read.API.Applicantions.Command.Kanbans;

namespace T.E.ERP.Read.API.Applicantions.CommandHandler.KanbanHandler
{
    public class templateHandler3 : IRequestHandler<templateCommand3, APIResult<List<MaterialRuNumDto>>>
    {
        private readonly IBaseRepository<SalesReturns> _salesReturns;

        public templateHandler3(IBaseRepository<SalesReturns> salesReturns)
        {
            _salesReturns = salesReturns;
        }

        public async Task<APIResult<List<MaterialRuNumDto>>> Handle(templateCommand3 request, CancellationToken cancellationToken)
        {
            var result = new APIResult<List<MaterialRuNumDto>>()
            {
                Code = APIEnum.查询成功,
                Msg = APIEnum.查询成功.ToString(),
            };
            // 获取所有销售退货数据
            var allReturns =await _salesReturns.GetAll();

            // 按物料名称分组并计算总入库量
            var materialStats = allReturns
                .Where(x => !string.IsNullOrEmpty(x.WuliaoName)) // 过滤空物料名
                .GroupBy(x => x.WuliaoName)
                .Select(g => new MaterialRuNumDto
                {
                    WuliaoName = g.Key,
                    TotalRuNum = g.Sum(x => x.RuNum)
                })
                .OrderByDescending(x => x.TotalRuNum) // 按入库量降序
                .ToList();

            result.data = materialStats;
            return await Task.FromResult(result);
        }
    }

    /// <summary>
    /// 物料入库数量DTO
    /// </summary>
    public class MaterialRuNumDto
    {
        /// <summary>
        /// 物料名称
        /// </summary>
        public string? WuliaoName { get; set; }

        /// <summary>
        /// 入库总量
        /// </summary>
        public int TotalRuNum { get; set; }
    }
}
